import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';

export function activate(context: vscode.ExtensionContext) {
    // 注册命令
    const disposable = vscode.commands.registerCommand('gitignore-toggle.addToGitignore', async (uri: vscode.Uri) => {
        if (!uri) {
            // 如果没有提供URI，尝试从当前活动编辑器获取
            const editor = vscode.window.activeTextEditor;
            if (!editor) {
                vscode.window.showErrorMessage('请先打开一个文件或在文件资源管理器中选择一个文件/目录');
                return;
            }
            uri = editor.document.uri;
        }

        try {
            await toggleGitignoreEntry(uri);
        } catch (error: any) {
            vscode.window.showErrorMessage(`操作失败: ${error.message}`);
        }
    });

    context.subscriptions.push(disposable);
}

export function deactivate() {}

async function toggleGitignoreEntry(uri: vscode.Uri) {
    const workspaceFolder = vscode.workspace.getWorkspaceFolder(uri);
    if (!workspaceFolder) {
        vscode.window.showErrorMessage('所选文件/目录不在工作区中');
        return;
    }

    const gitignorePath = path.join(workspaceFolder.uri.fsPath, '.gitignore');
    const relativePath = path.relative(workspaceFolder.uri.fsPath, uri.fsPath);
    
    // 规范化路径分隔符为Unix风格（gitignore使用/作为路径分隔符）
    const gitignoreEntry = relativePath.split(path.sep).join('/');

    // 检查并创建.gitignore文件（如果不存在）
    if (!fs.existsSync(gitignorePath)) {
        fs.writeFileSync(gitignorePath, '', 'utf8');
    }

    // 读取并解析.gitignore内容
    let content = fs.readFileSync(gitignorePath, 'utf8');
    const lines = content.split('\n');
    
    // 检查条目是否存在
    const entryExists = lines.some(line => line.trim() === gitignoreEntry);
    
    // 更新.gitignore内容
    if (entryExists) {
        // 移除条目
        const updatedLines = lines.filter(line => line.trim() !== gitignoreEntry);
        content = updatedLines.join('\n');
        vscode.window.showInformationMessage(`已从.gitignore中移除: ${gitignoreEntry}`);
    } else {
        // 添加条目
        content += content ? `\n${gitignoreEntry}` : gitignoreEntry;
        vscode.window.showInformationMessage(`已添加到.gitignore: ${gitignoreEntry}`);
    }

    // 保存更新后的.gitignore文件
    fs.writeFileSync(gitignorePath, content, 'utf8');
    
    // 刷新Git视图
    await vscode.commands.executeCommand('git.refresh');
}    